package com.msb.smsgateway.runnable;

import com.msb.common.constart.CacheConstant;
import com.msb.common.constart.RabbitMQConstants;
import com.msb.common.constart.SmsConstant;
import com.msb.common.model.StandardReport;
import com.msb.common.util.CMPP2DeliverUtil;
import com.msb.common.util.CMPPDeliverMapUtil;
import com.msb.common.util.SpringUtil;
import com.msb.smsgateway.feign.BeaconCacheClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @Author: lmf
 * @Create: 2025/3/22 14:44
 * @module
 */
@Slf4j
public class DeliverRunnable implements Runnable {
    private RabbitTemplate rabbitTemplate = SpringUtil.getBeanByClass(RabbitTemplate.class);

    private BeaconCacheClient cacheClient = SpringUtil.getBeanByClass(BeaconCacheClient.class);


    private final String DELIVRD = "DELIVRD";

    private long msgId;

    /**
     * 状态
     */
    private String stat;

    public DeliverRunnable(long msgId, String stat) {
        this.msgId = msgId;
        this.stat = stat;
    }

    @Override
    public void run() {
        //1、基于msgId拿到临时存储的Report对象
        StandardReport report = CMPPDeliverMapUtil.remove(msgId + "");
        //2、确认当前短信发送的最终状态
        if (DELIVRD.equals(stat)) {
            // 短信发送成功
            report.setReportState(SmsConstant.SEND_SUCCESS);

        } else {
            report.setReportState(SmsConstant.SEND_FAIL);
            report.setErrorMessage(CMPP2DeliverUtil.getResultMessage(stat));
        }

        String FIELD = "isCallback";
        //3、客户状态报告推送，让网关模块查询缓存，当前客户是否需要状态报告推送
        // 查询当前客户的isCallback

        Integer isCallback = cacheClient.hGetInteger(CacheConstant.CLIENT_BUSINESS + report.getApiKye(), FIELD);
        if (isCallback == 1) {
            // 如果需要回调，再查询客户的回调地址
            String callbackUrl = cacheClient.hGetToString(CacheConstant.CLIENT_BUSINESS + report.getApiKye(),
                    "callbackUrl");
            if (StringUtils.isNotEmpty(callbackUrl)) {
                report.setIsCallback(isCallback);
                report.setCallbackUrl(callbackUrl);
                // 发送消息到RabbitMQ
                log.info("发送消息给客户");
                rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_SEND_CLIENT, report);
            }
        }
        log.info("短信发送结束，report={}", report);

        //4、发送消息，让搜索模块对之前写入的信息做修改，这里需要做一个死信队列，延迟10s发送修改es信息的消息
        // 声明好具体的交换机和队列后，直接发送report到死信队列即可
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_GATEWAY_DEAD_QUEUE, report);
    }
}
